class ReviewsController < ApplicationController
  # GET /reviews
  # GET /reviews.xml
  layout "front_page"
  before_filter :admin?,:only=>[:list,:update]
  before_filter :login_required,:only=>[:new,:create,:destroy]
  def index
    @reviews = Review.paginate(:all,:page=>params[:page])
    @page_title="留言中心"
    @page_nav=">&nbsp;"+@page_title
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @reviews }
    end
  end
  def list
    @reviews = Review.paginate(:all,:page=>params[:page],:joins=>" as a inner join users u on u.id=a.user_id",:select=>"a.*,u.login")
    respond_to do |format|
      format.html { render :layout=>"admin"}
      format.xml  { render :xml => @reviews }
    end
  end

  # GET /reviews/1
  # GET /reviews/1.xml
  def show
    @review = Review.find(params[:id])
    @comment=Comment.new
    @page_title=@review.title
    @page_nav="><a href='#{reviews_path}'>留言中心</a>>&nbsp;"+@page_title
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @review }
    end
  end

  # GET /reviews/new
  # GET /reviews/new.xml
  def new
    @review = Review.new
    @page_title="发布留言"
    @page_nav="><a href='#{reviews_path}'>留言中心</a>>&nbsp;"+@page_title
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @review }
    end
  end

  # GET /reviews/1/edit
  def edit
    @review = Review.find(params[:id])
  end

  # POST /reviews
  # POST /reviews.xml
  def create
    @page_title="发布留言"
    @page_nav="><a href='#{reviews_path}'>留言中心</a>>&nbsp;"+@page_title
    @review = Review.new(params[:review])
    @review.user_id=session[:user_id]
    respond_to do |format|
      if @review.save
        flash[:notice] = '谢谢！留言成功！'
        format.html { redirect_to(reviews_path) }
        format.xml  { render :xml => @review, :status => :created, :location => @review }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @review.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /reviews/1
  # PUT /reviews/1.xml
  def update
    @review = Review.find(params[:id])

    respond_to do |format|
      if @review.update_attributes(params[:review])
        flash[:notice] = 'Review was successfully updated.'
        format.html { redirect_to(@review) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @review.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /reviews/1
  # DELETE /reviews/1.xml
  def destroy
    @review = Review.find(params[:id])
    @review.destroy

    respond_to do |format|
      format.html { redirect_to(reviews_url) }
      format.js do render :update do |page|
          page.remove("review#{@review.id}")
        end
      end
      format.xml  { head :ok }
    end   
  end
end

